<?php
class system_session_handler_table extends system_session_model implements system_session_handler_interface {

	protected $_request = null;
	
	public function __construct() {
		$this->_request = system_controller_front::getInstance()->getRequest();
	}

	/**
	 * @return system_controller_request_http
	 */
	public function getRequest() {
		return $this->_request;
	}
	
	public function __destruct() {
		system_session::writeClose();
	}
	
	public function open($save_path, $name) {
		return true;
	}
	
	public function close() {
		return true;
	}
	
	public function read($id) {
		$return = '';
		$this->delete('modified + lifetime < ' . time());
		if(!!($row = $this->fetchRow("sid = '$id'"))) {
			$return = $row->data;
		}
		return $return;
	}
	
	public function write($id, $data) {
		$data = array('modified' => time(), 'data' => (string) $data);
		$data['request_uri'] = substr($this->getRequest()->getRequestUri(), 0, 200);
		$data['referer'] = substr($this->getRequest()->getHeader('referer'), 0, 200);
		$data['passport_id'] = 0;//(int) system_passport::getInstance()->getStorage()->getId();
		$data['ip'] = $this->getRequest()->getClientIp(true);
		$data['host'] = $this->getRequest()->getHeader('host');
		
		if($this->fetchRow("sid = '$id'")) {
			if($this->update($data, "sid = '$id'")) {
				return true;
			}		
		} else {
			$data['user_agent'] = substr($this->getRequest()->getHeader('User-Agent'), 200);
			$data['lifetime'] = (int) system_session::getOptions('db_lifetime');
			$data['sid'] = $id;			
			if($this->insert($data)) {
				return true;
			}
		}		
		return true;
	}
	
	public function destroy($id) {
		$this->delete("sid = '$id'");
		return false;
	}
	
	public function gc($maxlifetime) {
		return true;
	}
	
}
